package INTROSE_MP;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OrderForm.java
 *
 * Created on Aug 1, 2011, 4:12:09 AM
 */
/**
 *
 * @author Paolo
 */
public class OrderForm extends javax.swing.JFrame {
    
    

    /** Creates new form OrderForm */
    public OrderForm() {
        
        
        model0 = new DefaultTableModel();
        initComponents();
        
        model0.addColumn("Product Code");
        model0.addColumn("Product Name");
        model0.addColumn("Size");
        model0.addColumn("Items in Stock");
        model0.addColumn("Price"); 
        tblProducts.setModel(model0);
       
        model1 = new DefaultTableModel();
        model1.addColumn("Product Code");
        model1.addColumn("Product Name");
        model1.addColumn("Size");
        model1.addColumn("Price");
        model1.addColumn("Quantity");
        
        model2 = new DefaultTableModel();
        model2.addColumn("Client ID");
        model2.addColumn("Client Name");
        fillClientsTable.setModel(model2);
        
        
        
        tblOrder.setModel(model1);

        jScrollPane1.setViewportView(tblProducts);
        ResultSet rSet = Main.doSelect("SELECT productcode,product_name,size,quantity,price FROM product");
        fillTableOrders(rSet);
        
        ResultSet rSet1 = Main.doSelect("SELECT clientID, clientname FROM introse.client");
        fillClientList(rSet1);
       
        rowData = new Vector<Vector>();
        //jScrollPane1.setViewportView(tblOrder);
        
    }

    
    private void fillTableOrders(ResultSet rSet)
    { DefaultTableModel dm = (DefaultTableModel)tblProducts.getModel();
      dm.getDataVector().removeAllElements();
        try {
            while(rSet.next())
            { Vector<String> row = new Vector<String>();
              row.add(rSet.getInt(1)+"");
              row.add(rSet.getString(2));
              row.add(rSet.getString(3));
              row.add(rSet.getInt(4)+"");
              row.add(rSet.getInt(5)+"");
              model0.addRow(row);
              
            }
        } catch (SQLException ex) {
            Logger.getLogger(OrderForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
     
    private void fillClientList(ResultSet rSet)
   {
      DefaultTableModel dm = (DefaultTableModel)fillClientsTable.getModel();
      dm.getDataVector().removeAllElements();
        try {
            while(rSet.next())
            { Vector<String> row = new Vector<String>();
              row.add(rSet.getInt(1)+"");
              row.add(rSet.getString(2));
              model2.addRow(row);
              
            }
        } catch (SQLException ex) {
            Logger.getLogger(OrderForm.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel2 = new javax.swing.JLabel();
        clientNameTxt = new javax.swing.JTextField();
        quantityField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        addSelectButton = new javax.swing.JButton();
        cancelSelectButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblProducts = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblOrder = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        fillClientsTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Order Form");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Client ID:");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 10, -1, -1));
        getContentPane().add(clientNameTxt, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 10, 110, -1));
        getContentPane().add(quantityField, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 180, 31, -1));

        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("Quantity:");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 180, -1, -1));

        addSelectButton.setText("===>");
        addSelectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addSelectButtonActionPerformed(evt);
            }
        });
        getContentPane().add(addSelectButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 220, -1, -1));

        cancelSelectButton.setText("<===");
        cancelSelectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelSelectButtonActionPerformed(evt);
            }
        });
        getContentPane().add(cancelSelectButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 250, -1, -1));

        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        getContentPane().add(saveButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 310, -1, -1));

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        getContentPane().add(cancelButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 310, -1, -1));

        tblProducts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tblProducts);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, 360, 160));

        tblOrder.setAutoCreateColumnsFromModel(true);
        jScrollPane2.setViewportView(tblOrder);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 180, 360, 160));

        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Products:");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, -1, -1));

        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Products ordered:");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 150, -1, -1));

        fillClientsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(fillClientsTable);

        getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 40, 347, 91));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/BG.jpg"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(-40, 0, 980, 360));

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void cancelSelectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelSelectButtonActionPerformed
// TODO add your handling code here:
    try{
        model1.removeRow(tblOrder.getSelectedRow());
       
    }catch(ArrayIndexOutOfBoundsException e){
        JOptionPane.showMessageDialog(this, "Please select a product to cancel.");
    }
}//GEN-LAST:event_cancelSelectButtonActionPerformed

private void addSelectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSelectButtonActionPerformed
// TODO add your handling code here:
    int i = tblProducts.getSelectedRow();
    int stockquantity = 0;
    int pQuantity=0;
    try{
    stockquantity = Main.getStock(Integer.parseInt((String)tblProducts.getValueAt(tblProducts.getSelectedRow(), 0)));
    Pattern p = Pattern.compile("([0-9])+");
    Matcher m = p.matcher(quantityField.getText());
    boolean b = m.matches(); //true - match yung "[0-9]";
    
    pQuantity = Integer.parseInt(quantityField.getText());
    
    if(!b){
        JOptionPane.showMessageDialog(this, "Please enter a number.");
    }
    else if(pQuantity>stockquantity){
         JOptionPane.showMessageDialog(this, "The value you entered is greater than the number of stocks.");
    }
    else{
    Vector row = new Vector();
    Vector temp = (Vector)model0.getDataVector().elementAt(i);
    row.add(temp.elementAt(0));
    row.add(temp.elementAt(1));
    row.add(temp.elementAt(2));
    row.add(temp.elementAt(4));
    row.add(quantityField.getText());
    model1.addRow(row);
    row.add(temp.elementAt(3));
    rowData.add(row);
    }
    }
    catch(ArrayIndexOutOfBoundsException e){
        JOptionPane.showMessageDialog(this, "Please select a product to order");
        
    }
}//GEN-LAST:event_addSelectButtonActionPerformed

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
// TODO add your handling code here:
    
    int currOrderCode = Main.getCurrentOrderCode();
    int clientID = 0;
    int productCode, quantity, stock;
    String str = "Processing";
    boolean b=false;
    
    
    if(!clientNameTxt.getText().isEmpty() && clientNameTxt.getText()!=null){
     clientID = Integer.parseInt(clientNameTxt.getText());
     b=Main.checkID(clientID);
        if(b){
    currOrderCode++;
    clientID = Integer.parseInt(clientNameTxt.getText());
    for(int i = 0; i < tblOrder.getRowCount(); i++) {        
        productCode = Integer.parseInt((String)(tblOrder.getModel().getValueAt(i, 0)));
        quantity = Integer.parseInt((String)(tblOrder.getModel().getValueAt(i, 4)));
        stock = Integer.parseInt((String)(rowData.elementAt(i).elementAt(5)));
        Main.saveOrder(currOrderCode, clientID, str, productCode, stock, quantity);
    }
       
    JOptionPane.showMessageDialog(this, "The order code is: "+currOrderCode);
    this.dispose();
    ManagerWindow manager = new ManagerWindow();
    manager.setVisible(true);
    manager.setLocationRelativeTo(null);
        }
        else
            JOptionPane.showMessageDialog(this, "There is no client with that ID.");
        
    }
    else
        JOptionPane.showMessageDialog(this, "Please enter a client ID.");
    

  
}//GEN-LAST:event_saveButtonActionPerformed

private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
// TODO add your handling code here:
   // OrderForm order = new OrderForm();
       
        this.dispose();
        ManagerWindow manager = new ManagerWindow();
        manager.setVisible(true);
        manager.setLocationRelativeTo(null);
    
}//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    /**public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new OrderForm().setVisible(true);
            }
        });
    }**/
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addSelectButton;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton cancelSelectButton;
    private javax.swing.JTextField clientNameTxt;
    private javax.swing.JTable fillClientsTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField quantityField;
    private javax.swing.JButton saveButton;
    private javax.swing.JTable tblOrder;
    private javax.swing.JTable tblProducts;
    // End of variables declaration//GEN-END:variables
private DefaultTableModel model0;
private DefaultTableModel model1;
private DefaultTableModel model2;
private Vector<Vector> rowData;

}
